﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Client.Models.SystemManage;

using Newtonsoft.Json;
using System.Data;
using System.IO;
using System.Text;
using System.Security.Cryptography;

namespace Client.Controllers
{
    public class EmployeeController : Controller
    {
        //
        // GET: /Employee/
        ServiceReference1.WebService1SoapClient client = new ServiceReference1.WebService1SoapClient();
        public ActionResult Index()
        {
            if (Session["LoginInfo"] == null)
                return RedirectToAction("Login");
            ServiceReference1.EmployeeLoginInfo_Model login = Session["LoginInfo"] as ServiceReference1.EmployeeLoginInfo_Model;
            ViewBag.UserName = login.EmployName;
            return View();
        }

        /// <summary>
        /// 查询登录人的基本信息是否得到完善，进行提示
        /// </summary>
        /// <returns></returns>
        public int ShowBasicInfo()
        {
            //接收登录信息
            ServiceReference1.EmployeeLoginInfo_Model login = Session["LoginInfo"] as ServiceReference1.EmployeeLoginInfo_Model;

            //查询登录人的基本信息是否得到完善
            if (client.GetIsBasicInfo(login.EmployID) == null)
                return -1;
            else
            {
                return client.GetIsBasicInfo(login.EmployID).InfoState;
            }
            //如果返回为-1，则直接弹出完善个人信息的窗口
            //如果返回为0，则直接根据角色权限进行判断所拥有的操作
            //如果返回为1，则直接显示提示信息为正在审核中，请等待
            //如果返回为2，则直接提示信息提交失败，请重新提交，弹出完善个人信息窗口
        }

        #region 填充下拉框信息

        /// <summary>
        /// 获取政治面貌列表信息
        /// </summary>
        /// <returns></returns>
        public string GetPoliticalList()
        {
            return client.GetPoliticalList();
        }
        /// <summary>
        /// 获取学历列表信息
        /// </summary>
        /// <returns></returns>
        public string GetEducationList()
        {
            return client.GetEducationList();
        }

        /// <summary>
        /// 权限信息显示
        /// </summary>
        /// <returns></returns>
        public string GetLimitInfo()
        {
            ServiceReference1.EmployeeLoginInfo_Model login = Session["LoginInfo"] as ServiceReference1.EmployeeLoginInfo_Model;
            return JsonConvert.SerializeObject(client.GetLimitInfo(login.DeptID,login.PositionID));
        }

        /// <summary>
        /// 前台导航显示
        /// </summary>
        /// <returns></returns>
        public string JsonString()
        {
            StringBuilder json = new StringBuilder();
            ServiceReference1.EmployeeLoginInfo_Model login = Session["LoginInfo"] as ServiceReference1.EmployeeLoginInfo_Model;

            List<ServiceReference1.LimitInfo_Model> list = client.GetLimitInfo(login.DeptID, login.PositionID).ToList();
            json.Append("{");
            json.Append("\"menus\":[");
            for (int i = 0; i < list.Count; i++)
            {

                if (list[i].Pid == 0)
                {
                    json.Append("{");
                    //拼接menuid
                    json.Append("\"menuid\":\"" + list[i].menuid + "\",");
                    //拼接icon
                    json.Append("\"icon\":\"" + list[i].icon + "\",");
                    //拼接menuname
                    json.Append("\"menuname\":\"" + list[i].menuname + "\",");
                    json.Append("\"menus\":[");
                    for (int j = 0; j < list.Count; j++)
                    {

                        //子集的PID == 父级的 menuid
                        if (list[i].menuid == list[j].Pid)
                        {
                            json.Append("{");
                            //拼接menuid
                            json.Append("\"menuid\":\"" + list[j].menuid + "\",");
                            //拼接menuname
                            json.Append("\"menuname\":\"" + list[j].menuname + "\",");
                            //拼接icon
                            json.Append("\"icon\":\"" + list[j].icon + "\",");
                            //拼接url
                            json.Append("\"url\":\"" + list[j].url + "\"");

                            json.Append("},");
                        }

                    }
                    json.Remove(json.Length - 1, 1);
                    json.Append("]},");
                }

            }
            json.Remove(json.Length - 1, 1);
            json.Append("]}");

            return json.ToString();
        }

        #endregion

        #region 员工完善信息

        /// <summary>
        /// 完善基础信息
        /// </summary>
        /// <returns></returns>
        public ActionResult CompleteInfo(int id)
        {
            //接收登录信息
            ServiceReference1.EmployeeLoginInfo_Model login = Session["LoginInfo"] as ServiceReference1.EmployeeLoginInfo_Model;

            ViewBag.EmployeeName = login.EmployName;
            ViewBag.id = id;
            ServiceReference1.EmployeeBasicInfo_Model basic = client.GetBasicEmployeeInfoById(login.EmployID);
            return View();
        }

        public string BackFill()
        {
            //接收登录信息
            ServiceReference1.EmployeeLoginInfo_Model login = Session["LoginInfo"] as ServiceReference1.EmployeeLoginInfo_Model;
            ServiceReference1.EmployeeBasicInfo_Model basic = client.GetBasicEmployeeInfoById(login.EmployID);
            if (basic != null)
                return JsonConvert.SerializeObject(basic);
            else
                return "";
        }
        public ActionResult CompleteInfoDo(ServiceReference1.EmployeeBasicInfo_Model basic, HttpPostedFileBase file)
        {
            #region 上传图片

            //图片所在文件夹的绝对路径
            string savePath = Server.MapPath("/image/");
            //查询文件夹是否存在，不存在则创建
            if (!Directory.Exists(savePath))
                Directory.CreateDirectory(savePath);

            int be;
            MemoryStream ms = new MemoryStream();
            while ((be = file.InputStream.ReadByte()) != -1)
            {
                ms.WriteByte((byte)be);
            }

            //文件所在的虚拟路径
            string url = "/image/" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";
            FileStream fs = new FileStream(Server.MapPath(url), FileMode.Create);
            ms.WriteTo(fs);

            //释放流
            fs.Dispose();
            ms.Dispose();

            #endregion

            //赋值
            basic.EmployeePhoto = url;
            ServiceReference1.EmployeeLoginInfo_Model login = Session["LoginInfo"] as ServiceReference1.EmployeeLoginInfo_Model;
            basic.EmployID = login.EmployID;
            //删除数据表中关于该员工的基础信息
            client.DeleteBasicEmployeeInfoById(login.EmployID);
            if (client.InsertBasicEmployeeInfo(basic) > 0)
            {
                return RedirectToAction("Index");
            }
            else
            {
                return Content("<script>alert('提交成功，请等待。。。');location.href='/Employee/CompleteInfo';</script>");
            }
        }

        #endregion

        #region 用户登录处理

        public ActionResult Login()
        {
            return View();
        }
        public int LoginDo(string Account, string Password)
        {
            //接收登录后的信息
            ServiceReference1.EmployeeLoginInfo_Model login = client.IsLogin(Account, Password);

            //判断登录信息
            if (login == null)
                return 0;
            else
            {
                Session["LoginInfo"] = login;
                return 1;
            }
        }

        #endregion

        #region 用户系统操作

        #region 角色/部门管理

        /// <summary>
        /// 角色管理/部门管理
        /// </summary>
        /// <returns></returns>
        public ActionResult RoleManage()
        {
            return View();
        }

        /// <summary>
        /// 部门/角色信息显示，支持模糊查询
        /// </summary>
        /// <param name="DeptName">部门名称</param>
        /// <returns></returns>
        public string RoleList(string DeptName)
        {
            return JsonConvert.SerializeObject(client.GetRoleList(DeptName));
        }

        /// <summary>
        /// 添加部门/角色信息
        /// </summary>
        /// <param name="dept">部门实体类传参</param>
        /// <returns></returns>
        public int InsertDeptInfo(string DeptName)
        {
            ServiceReference1.Dept_Model dept = new ServiceReference1.Dept_Model();
            dept.DeptName = DeptName;
            return client.InsertDeptInfo(dept);
        }

        /// <summary>
        /// 根据角色ID显示部门
        /// </summary>
        /// <param name="id">角色ID</param>
        /// <returns></returns>
        public string GetEmployeeByDeptID(int id)
        {
            return JsonConvert.SerializeObject(client.GetEmployeeBasicInfo1().Where(p => p.DeptID == id).ToList());
        }

        #endregion

        #region 用户角色分配

        public ActionResult GiveEmpAllotDept()
        {
            return View();
        }
        /// <summary>
        /// 员工信息/分页显示
        /// </summary>
        /// <param name="PageIndex"></param>
        /// <param name="PageSize"></param>
        /// <param name="EmployeeID"></param>
        /// <returns></returns>
        public string EmployeeInfoList(int PageIndex, int PageSize,string EmployeeID)
        {
            int count;
            //调用员工信息分页显示
            var list = JsonConvert.SerializeObject(client.GetEmployeeBasicInfo2(PageIndex, PageSize, int.Parse(EmployeeID), out count));
            //拼接json串
            return "{\"list\":" + list + ",\"Count\":" + count + "}";
        }
        /// <summary>
        /// 职位信息
        /// </summary>
        /// <returns></returns>
        public string PositionList()
        {
            return client.GetPositionList();
        }

        /// <summary>
        /// 执行用户角色分配
        /// </summary>
        /// <param name="EmpId">员工id</param>
        /// <param name="DeptID">部门ID</param>
        /// <param name="PositionID">职位ID</param>
        /// <returns></returns>
        public int SaveEmpDeptAllot(int EmpId, int DeptID, int PositionID)
        {
            return client.SaveEmpDeptAllot(EmpId, DeptID, PositionID);
        }

        #endregion

        #region 角色权限管理

        /// <summary>
        /// 为部门/职位分配权限
        /// </summary>
        /// <returns></returns>
        public ActionResult GiveDeptAllotLimit()
        {
            return View();
        }

        /// <summary>
        /// 为部门/职位分配权限
        /// </summary>
        /// <returns></returns>
        public int GiveDeptAllotLimitDo(int DeptId, int PositionId, string limitIds)
        {
            return client.GiveDeptAllotLimit(DeptId, PositionId, limitIds);
        }


        /// <summary>
        /// 反填前台复选框
        /// </summary>
        /// <param name="DeptId">部门 id</param>
        /// <param name="PositionID">职位 id</param>
        /// <returns></returns>
        public string BackFillLimit(int DeptId, int PositionID)
        {
            return JsonConvert.SerializeObject(client.GetLimitInfo(DeptId, PositionID));
        }

        #endregion

        #region 用户管理

        /// <summary>
        /// 用户管理
        /// </summary>
        /// <returns></returns>
        public ActionResult ManageEmployee()
        {
            return View();
        }
        public string EmployeeInfoList2(int PageIndex, int PageSize, string EmployeeName)
        {
            int count;
            //调用员工信息分页显示
            var list = JsonConvert.SerializeObject(client.GetEmployeeBasicInfo3(PageIndex, PageSize, EmployeeName, out count));
            //拼接json串
            return "{\"list\":" + list + ",\"Count\":" + count + "}";
        }


        /// <summary>
        /// 注册用户信息
        /// </summary>
        /// <returns></returns>
        public ActionResult AddManageEmployee()
        {
            
            return View();
        }
        //注册用户信息
        public int AddManageEmployeeDo(ServiceReference1.EmployeeLoginInfo_Model register)
        {
            return client.RegisterEmployee(register);
        }

        //员工基础信息审核
        public ActionResult CheckEmpInfoState(int EmpId)
        {
            return View(client.GetBasicEmployeeInfoById(EmpId));
        }

        //提交审核状态
        public int SubmitInfoState(int InfoState,int EmpId)
        {
            return client.UpdateBasicInfoState(InfoState, EmpId);
        }

        //员工当前前状态
        public ActionResult CheckEmpLoginState(int EmpId, int PersonState)
        {
            ViewBag.PersonState = PersonState;
            ViewBag.EmpId = EmpId;
            return View();
        }

        //提交当前状态
        public int SubmitLoginState(int PersonState, int EmpId)
        {
            return client.UpdateLoginInfoState(PersonState, EmpId);
        }

        #endregion

        #endregion

        /// <summary>
        /// 安全退出
        /// </summary>
        public ActionResult loginOut()
        {
            Session["LoginInfo"] = null;
            return RedirectToAction("Index");
        }

        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="newpass"></param>
        /// <returns></returns>
        public string EditPassword(string newpass)
        {
            ServiceReference1.EmployeeLoginInfo_Model login = Session["LoginInfo"] as ServiceReference1.EmployeeLoginInfo_Model;
            Session["LoginInfo"] = null;
            if(Md5Hash(newpass)==client.EditPassword(login.EmployID, newpass))
            {
                return newpass;
            }

            return "失败";
        }

        /// <summary>
        /// 输入原密码返回加密后的密文
        /// </summary>
        /// <param name="input">输入的密码</param>
        /// <returns></returns>
        private string Md5Hash(string input)
        {
            MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
            byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));
            StringBuilder sBuilder = new StringBuilder();
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            return sBuilder.ToString();
        }
    }
}
